package com.brooks.demo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock 尝试锁定tryLock
 *
 * @Author mihutu
 * @Date 2020/10/18 12:21
 * @Version 1.0
 */
public class DemoReentrantLock3 {
    Lock lock = new ReentrantLock();
    void m1() {
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    void m2() {
        boolean isLock = false;
        try {
//            使用tryLock尝试锁定，不管锁定与否，方法都将继续执行
//            可以使用返回值来确定是否拿到锁
//            也可以指定tryLock的时间
            isLock = lock.tryLock(5,TimeUnit.SECONDS);
            System.out.println("m2===="+isLock);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(isLock) {
                lock.unlock();
            }
        }
    }
    public static void main(String[] args) {
        DemoReentrantLock3 t = new DemoReentrantLock3();
        new Thread(t::m1).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(t::m2).start();
    }
}